﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using JM.JCY.BusinessEntity;
using JM.JCY.Proxy;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Common;
using Microsoft.SharePoint;
using JM.JCY.Common.Utilities;

namespace JM.JCY.SharePointComponent.Announcement.EditAnnounce
{
    public partial class EditAnnounceUserControl : UserControl
    {
        public int _announceId
        {
            set { ViewState["_announceId"] = value; }
            get { return (int)ViewState["_announceId"]; }
        }

        public string _attachmentUrl
        {
            set { ViewState["_attachmentUrl"] = value; }
            get { return (string)ViewState["_attachmentUrl"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["AnnounceId"] != null)
                {
                    _announceId = Int32.Parse(Request.QueryString["AnnounceId"]);
                }
                using (AnnounceProxy proxy = new AnnounceProxy())
                {
                    AnnounceDataSet.T_AnnounceDataTable announceDT = proxy.GetAnnounce(_announceId, string.Empty, string.Empty);
                    AnnounceDataSet.T_Announce_ReceiverDataTable receiverDT = proxy.GetAnnounceReceiverById(_announceId);

                    Session["AnnounceDT"] = announceDT;
                    Session["AnnounceReceiverDT"] = receiverDT;
                    if (announceDT.Rows.Count > 0)
                    {
                        AnnounceDataSet.T_AnnounceRow annouceRow = announceDT[0];
                        this.txtSubject.Text = annouceRow.Subject;
                        this.txtSummary.Text = annouceRow.Summary;

                        // Add by Hong Liang 2012-05-02
                        if (!annouceRow.IsAttachmentUrlNull())
                            _attachmentUrl = annouceRow.AttachmentUrl;
                        else
                            _attachmentUrl = string.Empty;

                        // get all user from user info table
                        using (UserManagementProxy userProxy = new UserManagementProxy())
                        {
                            DataSetUserManagement.T_UserInfoDataTable userDT = userProxy.GetUser(0, string.Empty);

                            // delete user from left menu if exsit in right
                            foreach (AnnounceDataSet.T_Announce_ReceiverRow userExist in receiverDT.Rows)
                            {
                                for (int i = 0; i < userDT.Rows.Count; i++)
                                {
                                    if (userDT[i]["ID"].Equals(userExist.ReceiverUserId))
                                    {
                                        userDT.Rows.Remove(userDT[i]);
                                    }
                                }
                            }

                            if (userDT.Rows.Count > 0)
                            {
                                box1View.DataSource = userDT;
                                box1View.DataTextField = "UserName";
                                box1View.DataValueField = "ID";
                                box1View.DataBind();
                            }
                        }

                        // bind box view for current receiver
                        box2View.DataSource = receiverDT;
                        box2View.DataTextField = "ReceiverUserName";
                        box2View.DataValueField = "ReceiverUserId";
                        box2View.DataBind();
                    }

                }
            }
        }

        protected void imgSaveDraft_Click(object sender, ImageClickEventArgs e)
        {
            SaveAnnounce(JCYConstant.Status.Draft);
            Response.Redirect("ManageAnnounce.aspx");
        }

        protected void imgSavePublish_Click(object sender, ImageClickEventArgs e)
        {
            SaveAnnounce(JCYConstant.Status.Publish);
            Response.Redirect("ManageAnnounce.aspx");
        }

        protected void imgCancel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("ManageAnnounce.aspx");
        }

        private void SaveAnnounce(string status)
        {
            using (AnnounceProxy proxy = new AnnounceProxy())
            {
                // update announce table
                if (Session["AnnounceDT"] != null)
                {
                    var dt = (AnnounceDataSet.T_AnnounceDataTable)Session["AnnounceDT"];
                    if (dt.Rows.Count > 0)
                    {
                        var editRow = dt[0];
                        editRow.Subject = this.txtSubject.Text;
                        editRow.Summary = this.txtSummary.Text;
                        editRow.Status = status;

                        // add by Hong Liang 2012-05-02
                        if (this.filePicture.HasFile)
                        {
                            if (!string.IsNullOrEmpty(_attachmentUrl))
                            {  // add remove old attachment here
                                RemoveOldAttachment(_attachmentUrl);
                            }
                            editRow.AttachmentUrl = JCYSharePointHelper.UploadFileToAttachment(this.filePicture, Guid.NewGuid().ToString(), JCYConstant.SharePointListName.Attachment);
                            editRow.AttachmentName = this.filePicture.FileName;
                        }
                        JCY.Common.JCYUtility.UpdateCommonFields(editRow, "aa");
                        proxy.UpdateAnnouceSingle(dt);
                    }

                }
                // update announce receiver table
                if (Session["AnnounceReceiverDT"] != null)
                {
                    var receiverDT = (AnnounceDataSet.T_Announce_ReceiverDataTable)Session["AnnounceReceiverDT"];
                    if (receiverDT.Rows.Count > 0)
                    {
                        // delete old rows
                        for (int i = 0; i < receiverDT.Rows.Count; i++)
                        {
                            receiverDT.Rows[i].Delete();
                        }
                        proxy.UpdateAnnounceReceiverSingle(receiverDT);

                        // add new rows
                        // update announce receiver table
                        AnnounceDataSet.T_Announce_ReceiverDataTable annouceReceiverDT = new AnnounceDataSet.T_Announce_ReceiverDataTable();
                        string s = Request.Form[box2View.UniqueID];

                        foreach (var item in s.Split(','))
                        {
                            using (UserManagementProxy userProxy = new UserManagementProxy())
                            {
                                var newReceiver = annouceReceiverDT.NewT_Announce_ReceiverRow();
                                newReceiver.AnnounceId = _announceId;
                                newReceiver.ReceiverUserId = Int32.Parse(item);
                                newReceiver.ReceiverUserName = userProxy.GetUser(Int32.Parse(item), string.Empty)[0].UserName;
                                newReceiver.Status = JCY.Common.JCYConstant.ReadStatus.UnRead;
                                JCY.Common.JCYUtility.UpdateCommonFields(newReceiver, "aa");
                                annouceReceiverDT.AddT_Announce_ReceiverRow(newReceiver);
                            }

                            proxy.UpdateAnnounceReceiverSingle(annouceReceiverDT);
                        }
                    }
                }
            }

        }

        // add by Hong Liang 2012-05-02
        private void RemoveOldAttachment(string attchmentUrl)
        {
            string[] urlArr = attchmentUrl.Split('/');
            string guid = urlArr[urlArr.Length - 1].Substring(0, urlArr[urlArr.Length - 1].LastIndexOf('.'));

            using (SPWeb web = SPContext.Current.Web)
            {
                SPList list = web.Lists[JCYConstant.SharePointListName.Attachment];
                SPQuery query = new SPQuery();
                query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", guid);
                SPListItemCollection items = list.GetItems(query);
                if (items.Count > 0)
                {
                    SPListItem oListItem = items[0];
                    oListItem.Delete();
                    list.Update();
                }
            }

        }

    }
}
